package socialnetwork;

import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;

import view.ResearcherListPanel;
import db.DAOFacade;
import db.Database;
import dto.Researcher;

public class SocialNetwork {
	
	private static HashMap<String,Researcher> researchers = new HashMap<String,Researcher>();
	
	public static Researcher getResearcher(String name){
		if(researchers.containsKey(name))
			return researchers.get(name);
		else{
			Researcher r = new Researcher();
			r.setName(name);
			researchers.put(name, r);
			ResearcherListPanel.model.addResearcher(r);
			guardarResearcher(r);
			return r;
		}
	}
	
	public static boolean existsResearcher(String name){
		return researchers.containsKey(name);
	}
	
	public static void addResearcher(Researcher r){
		for(String s : r.getAlias()){
			researchers.put(s,r);
		}
		researchers.put(r.getName(),r);
		guardarResearcher(r);
	}
	
	private static void guardarResearcher(Researcher r){
		try {
			Database.getConnection();
			new DAOFacade().guardarInvestigador(r);
			Database.disconnect();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static Collection<Researcher> getResearchers(){
		return researchers.values();
	}
	
	public static void addResearchers(Collection<Researcher> researchers){
		for (Researcher r : researchers){
			addResearcher(r);
			ResearcherListPanel.model.addResearcher(r);
		}
	}

	public static void eliminarInvestigador(Researcher r) {
		for (String s : r.getAlias()){
			researchers.remove(s);
		}
	}
}